package com.lee.sshclient;

import com.jcraft.jsch.*;

import java.io.*;

/**
 * Created by le on 2016/1/15.
 */
public class ShellClient {
    private String charset = "UTF-8"; // 设置编码格式
    private String user; // 用户名
    private String passwd; // 登录密码
    private String host; // 主机IP
    private int port;
    private JSch jsch;
    private Session session;
    private boolean closed = false;

    private Channel channel;
    private PipedOutputStream send;
    private OutputStream receive;

    /**
     *
     * @param user 用户名
     * @param passwd 密码
     * @param host 主机IP
     */
    /*public ShellClient(String user, String passwd, String host, int port) {
        this(user, passwd, host, port, new ByteArrayOutputStream());
    }*/

    /**
     *
     * @param user 用户名
     * @param passwd 密码
     * @param host 主机IP
     */
    public ShellClient(String user, String passwd, String host, int port, ShellCallback.Callback callback) {
        this.user = user;
        this.passwd = passwd;
        this.host = host;
        this.port = port;
        this.receive = new ShellCallback(callback, charset);
    }

    public void setReceive(OutputStream receive) {
        this.receive = receive;
    }

    public OutputStream getReceive() {
        return receive;
    }

    public String getUser() {
        return user;
    }

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

    public String getCharset() {
        return charset;
    }

    /**
     * 连接到指定的IP
     *
     * @throws JSchException
     */
    public void connect() throws JSchException {
        jsch = new JSch();
        session = jsch.getSession(user, host, port);
        session.setPassword(passwd);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
    }

   /* public void openChannel() throws JSchException, IOException {
        channel = null;
        channel = session.openChannel("shell");
        // 设置输入命令流
        PipedInputStream inPiped = new PipedInputStream();
        PipedOutputStream outPiped = new PipedOutputStream(inPiped);
        send = new BufferedWriter(new OutputStreamWriter(outPiped, charset));
        channel.setInputStream(inPiped);
        // 设置接收返回信息流
        receive = new ByteArrayOutputStream();
        channel.setOutputStream(receive);
        channel.connect();
    }
*/

    public void openChannel() throws JSchException, IOException {
        channel = null;
        channel = session.openChannel("shell");

        // 读取服务器返回消息
        {
            channel.setOutputStream(receive);
        }
        // 发送消息给服务器
        {
            send = new PipedOutputStream();
            PipedInputStream in = new PipedInputStream(send);
            channel.setInputStream(in);
        }
        channel.connect();
    }


    /**
     * 执行相关的命令
     */
    public void execShell(String command) throws IOException {
        if(channel == null || channel.isClosed()){
            throw new RuntimeException("连接没有打开");
        }
        if("3".equals(command)) {
            send.write(3);
        } else {
            send.write((command + (command.endsWith("\n") ? "" : "\n")).getBytes());
        }
        send.flush();
    }

    public void disconnect() {
        closed = true;
        closeQuietly(send, receive);
        if(channel != null) {
            channel.disconnect();
        }
        if(session != null) {
            session.disconnect();
        }
    }

    public void closeQuietly(Closeable... closeables) {
        if(closeables == null) {
            return ;
        }
        for(Closeable closeable: closeables) {
            if(closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public boolean isClosed() {
        return closed;
    }
}
